<template>
  <div class="ai_wrap" ref="scrollWrap">
    <div class="content">
      <div class="top_wrap">
        <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5077">
          <path
              d="M802.133333 170.666667v682.666666h-597.333333V170.666667h597.333333m0-85.333334h-597.333333a85.333333 85.333333 0 0 0-85.333333 85.333334v682.666666a85.333333 85.333333 0 0 0 85.333333 85.333334h597.333333a85.333333 85.333333 0 0 0 85.333334-85.333334V170.666667a85.333333 85.333333 0 0 0-85.333334-85.333334z"
              fill="#ffffff" p-id="5078"></path>
          <path
              d="M674.133333 298.666667h-341.333333a42.666667 42.666667 0 0 0 0 85.333333h341.333333a42.666667 42.666667 0 0 0 0-85.333333zM503.466667 469.333333h-170.666667a42.666667 42.666667 0 0 0 0 85.333334h170.666667a42.666667 42.666667 0 0 0 0-85.333334zM631.466667 640h-298.666667a42.666667 42.666667 0 0 0 0 85.333333h298.666667a42.666667 42.666667 0 0 0 0-85.333333z"
              fill="#ffffff" p-id="5079"></path>
        </svg>
        <h6 class="business_title">{{ title }}</h6>
      </div>
      <div class="form_wrap">
        <van-field
            v-model="userName"
            name="姓名"
            label="姓名"
            required
            placeholder="上传身份证自动识别"
        />
        <van-field
            v-model="userId"
            name="身份证号"
            label="身份证号"
            required
            placeholder="上传身份证自动识别"
        />
        <van-field
            v-model="phoneNumber"
            label="手机号"
            required
            placeholder="请输入手机号"
        />
        <div class="form_dt required"><p>身份证</p></div>
        <div class="upload_row">
          <van-uploader v-model="newMaterialA"
                        name="身份证正面"
                        :before-read="beforeRead"
                        :after-read="startUpload"
                        :deletable="true"
                        @oversize="onOversize"
                        :preview-options="previewObj"
                        @delete="file=>deleteImg(file,'身份证正面')"
                        :max-size="10*1024*1024"
                        class="idcard_a" preview-size="120"
                        :multiple=false max-count="1"/>
          <van-uploader v-model="newMaterialB"
                        name="身份证反面"
                        :before-read="beforeRead"
                        :after-read="startUpload"
                        :deletable="true"
                        @oversize="onOversize"
                        :preview-options="previewObj"
                        @delete="file=>deleteImg(file,'身份证反面')"
                        :max-size="10*1024*1024"
                        class="idcard_b" preview-size="120"
                        :multiple=false max-count="1"/>
        </div>
        <div v-if="loadingStatus===1">
          <div class="other_material_area" v-for="(item,index) in MaterialList" :key="item.id+index">
            <div :class="item.required=='true'?'form_dt required':'form_dt'">
              <p>{{ item.materialname }}</p>
              <span v-if="item.isform=='true'">
                <van-button icon="plus" type="primary" size="mini" plain color="#5482eb" @click="onlineForm(item)">
                在线生成
                </van-button>
              </span>
              <span v-if="item.emptytable!=''">
                <van-button icon="down" type="primary" size="mini" plain color="#5482eb" @click="downloadBlank(item.emptytable)">
                空表下载
                </van-button>
              </span>
            </div>
            <div class="sampleDownload" v-if="item.sampleArr.length>0">
                <van-button v-for="(sitem,sindex) in item.sampleArr" :key="sitem+'sample'+sindex" icon="down" type="primary" size="mini" plain color="#5482eb" @click="downloadBlank(sitem)">
                  <span v-if="sitem.indexOf('(') >= 0">{{sitem.substring(sitem.lastIndexOf('/')+1,sitem.indexOf('('))}}</span>
                  <span v-else>{{sitem.substring(sitem.lastIndexOf('/')+1,sitem.indexOf('.'))}}</span>
                </van-button>
            </div>
            <div class="upload_row">
              <van-uploader v-model="ruleList[item.id]"
                            :name="item.materialname"
                            :before-read="beforeRead"
                            :after-read="startUpload"
                            :deletable="true"
                            @oversize="onOversize"
                            :preview-options="previewObj"
                            @delete="file=>deleteImg(file,item.materialname)"
                            :max-size="10*1024*1024"
                            class="hkb" preview-size="120"
                            @click-preview="handlePreviewImage"
                            :multiple=false :max-count="item.papernum">
              </van-uploader>
            </div>
          </div>
        </div>
        <Loading v-if="loadingStatus === 0"></Loading>
        <div v-if="loadingStatus === -1" class="error_area">资料拉取失败，请<span class="retry"
                                                                                 @click="findMatterMaterial">重新拉取</span>
        </div>
      </div>
      <div v-if="loadingStatus===1" style="margin:30px 16px;">
        <van-button round block type="primary" @click="submit">
          提交
        </van-button>
      </div>
    </div>
  </div>
    <van-popup v-model:show="formShow" position="bottom" :style="{ height: '100%' }" closeable :lock-scroll="false" @closed="celanForm">
      <Loading v-if="onlineFormStatus === 0"></Loading>
      <div class="form_area" ref="popupScrollWrap">
        <div class="content popup_con">
          <h6>请填写表单后提交生成电子材料</h6>
          <li class="form_item" v-for="(it,ind) in onlineFormData" :key="it.model+ind">
            <!--签名-->
            <div v-if="it.type=='imgupload' && it.model.indexOf('sign') >= 0">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initSignCanvas(it)">
                <span>{{ it.name }}</span>
                <img class="sign_img" :src="inputData[it.model]"/>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--日期-->
            <div v-if="it.type=='time' || it.type=='date'">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initPopup(it,2)">
                <span>{{ it.name }}</span>
                <div>{{inputData[it.model]}}</div>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--文本-->
            <div v-if="it.type=='input'" class="setting_area">
              <van-field v-model="inputData[it.model]" :label="it.name" placeholder="请输入" :required="it.required=='true'"/>
            </div>
            <!--文本域-->
            <div v-if="it.type=='textarea'" class="setting_area">
              <van-field type="textarea" v-model="inputData[it.model]" :label="it.name" placeholder="请输入" :required="it.required=='true'"/>
            </div>
            <!--多选-->
            <div v-if="it.type=='checkbox'">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initPopup(it,3)">
                <span>{{ it.name }}</span>
                <div v-if="inputData[it.model]">已选{{inputData[it.model].length}}项</div>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--单选-->
            <div v-if="it.type=='radio'||it.type=='select'">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initPopup(it,4)">
                <span>{{ it.name }}</span>
                <div>{{inputData[it.model]}}</div>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--身份证-->
            <div v-if="it.type=='imgupload' && it.model.indexOf('idcard') >= 0">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initPopup(it,5)">
                <span>{{ it.name }}</span>
                <img class="sign_img" :src="getRealUrl(inputData,it.model)" :key="keyvalue"/>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--普通图片上传-->
            <div v-if="it.type=='imgupload' && it.model.indexOf('imgs') >= 0">
              <div :class="it.required=='true'?'setting_area required1':'setting_area'" @click="initPopup(it,6)">
                <span>{{ it.name }}</span>
                <img class="sign_img" :key="keyvalue" :src="getRealUrl(inputData,it.model)"/>
                <van-icon name="arrow" color="#cccccc"/>
              </div>
            </div>
            <!--table-->
            <div v-if="it.type.indexOf('table') >= 0 && tableObj[it.model].length>0">
              <div class="table_wrap" v-for="(titem,tindex) in tableObj[it.model]" :key="'table'+tindex">
                <div :class="it.required=='true'?'table_title required1':'table_title'">
                  <span>{{it.name+'('+(tindex+1)+')' }}</span>
                  <svg v-if="(tindex+1)==tableObj[it.model].length" @click="addTableItem(it.model)" class="add_icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4947"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m192 472c0 4.4-3.6 8-8 8H544v152c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V544H328c-4.4 0-8-3.6-8-8v-48c0-4.4 3.6-8 8-8h152V328c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v152h152c4.4 0 8 3.6 8 8v48z" p-id="4948" fill="#5482eb"></path></svg>
                </div>
                <div class="table_con" v-for="(tm,tx) in titem" :key="'table_item'+tx">
                  <van-field v-model="inputData[it.model][tindex][tm.model]" :label="tm.name" placeholder="请输入" :required="tm.required=='true'"/>
                </div>
              </div>
            </div>
          </li>
        </div>
      </div>
      <div class="form_btn">
        <van-button round block type="primary" @click="formSubmit">
          提交
        </van-button>
      </div>
    </van-popup>
    <van-popup class="popup_half" v-model:show="inputAreaType" position="bottom" :style="{ height: '50%',overflowY:'hidden' }">
      <!--签名-->
      <div  v-if="inputAreaType==1" style="overflow: hidden">
        <div class="van-picker__toolbar">
          <button type="button" class="van-picker__cancel van-haptics-feedback" @click="clearSignature">取消</button>
          <div class="van-picker__title van-ellipsis">请在下侧空白面板签名</div>
          <button type="button" class="van-picker__confirm van-haptics-feedback" @click="saveSignature">确认</button>
        </div>
        <canvas ref="signaturePad" width="400" height="400"></canvas>
      </div>
      <!--日期-->
      <van-datetime-picker
          v-if="inputAreaType==2"
          v-model="currentDate"
          type="date"
          title="选择年月日"
          @confirm="confirmInput"
          @cancel="cancelInput"
      />
      <!--多选-->
      <div  v-if="inputAreaType==3">
        <div class="van-picker__toolbar">
          <button type="button" class="van-picker__cancel van-haptics-feedback" @click="cancelInput">取消</button>
          <div class="van-picker__title van-ellipsis">可选择多项</div>
          <button type="button" class="van-picker__confirm van-haptics-feedback" @click="cancelInput">确认</button>
        </div>
        <van-checkbox-group v-model="inputData[currentModel]">
          <van-checkbox v-for="itemy in currentSelects" :key="itemy" :name="itemy" shape="square">{{itemy}}</van-checkbox>
        </van-checkbox-group>
      </div>
      <!--单选/下拉-->
      <van-picker
          v-if="inputAreaType==4"
          :columns="currentSelects"
          @confirm="confirmInput"
          @cancel="cancelInput"
      />
      <!--身份证上传-->
      <div  v-if="inputAreaType==5">
        <div class="van-picker__toolbar">
          <button type="button" class="van-picker__cancel van-haptics-feedback" @click="cancelInput">取消</button>
          <div class="van-picker__title van-ellipsis">上传身份证</div>
          <button type="button" class="van-picker__confirm van-haptics-feedback" @click="confirmInput">确认</button>
        </div>
        <van-uploader v-model="inputData[currentModel]"
                      v-if="currentModel=='idcard_front'"
                      name="idcardfront_popup"
                      :before-read="beforeRead"
                      :after-read="startUpload"
                      :deletable="true"
                      :key="'a'+popupKey"
                      @oversize="onOversize"
                      :preview-options="previewObj"
                      @delete="file=>deleteCardImg(file,currentModel)"
                      :max-size="10*1024*1024"
                      class="idcard_a id_pop" preview-size="120"
                      :multiple=false max-count="1"/>
        <van-uploader v-model="inputData[currentModel]"
                      v-if="currentModel=='idcard_back'"
                      name="idcardback_popup"
                      :before-read="beforeRead"
                      :after-read="startUpload"
                      :deletable="true"
                      :key="'b'+popupKey"
                      @oversize="onOversize"
                      :preview-options="previewObj"
                      @delete="file=>deleteCardImg(file,currentModel)"
                      :max-size="10*1024*1024"
                      class="idcard_b  id_pop" preview-size="120"
                      :multiple=false max-count="1"/>
      </div>
      <!--普通上传-->
      <div  v-if="inputAreaType==6">
        <div class="van-picker__toolbar">
          <button type="button" class="van-picker__cancel van-haptics-feedback" @click="cancelInput">取消</button>
          <div class="van-picker__title van-ellipsis">上传图片</div>
          <button type="button" class="van-picker__confirm van-haptics-feedback" @click="confirmInput">确认</button>
        </div>
        <van-uploader v-model="inputData[currentModel]"
                      name="imgs_popup"
                      :before-read="beforeRead"
                      :after-read="startUpload"
                      :deletable="true"
                      @oversize="onOversize"
                      :preview-options="previewObj"
                      @delete="file=>deleteCardImg(file,currentModel)"
                      :max-size="10*1024*1024"
                      class="hkb" preview-size="120"
                      :multiple=false max-count="1"/>
      </div>
    </van-popup>
</template>

<script>
import BScroll from 'better-scroll'
import SignaturePad from 'signature_pad'
import axios from "axios";
import Cookies from 'js-cookie'
import Loading from '@/components/Loading'

export default {
  name: 'HomeView',
  data() {
    return {
      items: [],
      company:{},
      keyvalue: 1,
      token: Cookies.get('token'),
      title: '',
      id: this.$route.query.id,
      userName: "",
      userId: "",
      address: "",
      idcard_front: "",
      idcard_back: "",
      onlineFormData: [],
      onlineFormStatus: 0,
      newMaterialA: [],
      newMaterialB: [],
      MaterialList: [],
      ruleList: {},
      businessLicense: [],
      applicationImg: [],
      newUploadObj: [],
      loadingStatus: 0,
      formShow: false,
      inputAreaType: 0,
      phoneNumber: '',
      previewObj: {
      },
      currentDate: new Date(),
      currentSelects: [],
      currentModel:"",
      currentMaterialId:"",
      currentMaterialName:"",
      inputData: {},
      signaturePad: null,
      popupScrollObj:null,
      tentativeUploadImg:"",
      tableObj:{},
      popupKey: Date.now()
    }
  },
  components: {Loading},
  created() {
    //事项办理材料清单
    this.findMatterMaterial()
    this.intoAiDo()
  },
  setup() {

  },
  methods: {
    intoAiDo(){
      const url = `https://www.pengzhou.org.cn/api/sys/user/getusers`;
      axios.get(url,{},{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }}).then(response => {
        if (response.data && response.data.success) {
          this.phoneNumber = response.data.tell
        }}).catch(error => {
      });
    },
    processedList(arr) {
      return arr.map(item => {
        return {
          ...item,
          sampleArr: item.sampletable!=""&&item.sampletable!=undefined?item.sampletable.split('|'):[]
        };
      });
    },
    getRealUrl(obj,target){
      if (!obj.hasOwnProperty(target) || obj[target].length == 0) return ""
      var fileArr = obj[target]
      return fileArr[0]['url']
    },
    handlePreviewImage(){
      setTimeout(() => {
        const previewTitle = document.querySelector('.van-image-preview__index');
        if (previewTitle) {
          previewTitle.textContent = "长按图片可保存至手机";
        }
      }, 50);
    },
    //比对材料必填
    addItem(item) {
      if (!this.items.includes(item)) {
        this.items.push(item);
      }
    },
    //电子表单提交
    formSubmit(){
      let submitObj = JSON.parse(JSON.stringify(this.inputData))
      //if (submitObj.hasOwnProperty('idcard_front')) {
      //  submitObj.idcard_front = submitObj.idcard_front[0].url;
      //}
      //if (submitObj.hasOwnProperty('idcard_back')) {
      //  submitObj.idcard_back = submitObj.idcard_back[0].url;
      //}
      const url = 'https://www.pengzhou.org.cn/api/znsp/getPdf';
      axios.post(url, {
        oid:this.$route.query.id,
        id:this.currentMaterialId,
        data:JSON.stringify(submitObj)
      }, {
        headers: {
          'token': this.token,
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.data && response.data.success) {
          //提交成功，获取返回图片地址
          this.ruleList[this.currentMaterialId] = []
          //this.ruleList[this.currentMaterialId]=response.data.data
          for(let i=0;i<response.data.data.length;i++){
            let file = {"status":"done","file":null,"content":"","url":response.data.data[i].filePath,"message":""}
            this.ruleList[this.currentMaterialId].push(file)
            let valueList = {
              url: response.data.data[i].filePath,
              name: this.currentMaterialName
            }
            this.newUploadObj.push(valueList)
          }
          this.formShow = false
          this.intoUserMaterials()
          this.clearFormData()
        } else {
          this.$toast('电子表单提交失败，请稍后重试');
        }
      }).catch(error => {
        this.$toast('电子表单提交失败，请稍后重试');
        console.error('Error:', error);
      });
    },
    initSignCanvas(item) {
      this.inputAreaType = 1
      this.currentModel = item.model
      this.$nextTick(() => {
        const canvas = this.$refs.signaturePad;
        this.signaturePad = new SignaturePad(canvas);
      })
    },
    initPopup(item,t){
      this.inputAreaType = t
      this.currentModel = item.model
      if(t==3||t==4){
        this.currentSelects = []
        item.options.forEach(item=>{
          this.currentSelects.push(item.value)
        })
      }
    },
    clearSignature() {
      this.signaturePad.clear();
      this.cancelInput()
    },
    saveSignature() {
      const signature = this.signaturePad.toDataURL();
      //转图片
      const url = "https://www.pengzhou.org.cn/api/znsp/toImage";
      axios.post(url,{
        data:signature
      },{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }}).then(response => {
        if (response.data && response.data.success) {
          this.inputData[this.currentModel]=response.data.url
          this.cancelInput()
        }else{
          this.$toast('签名失败');
        }}).catch(error => {
        console.error('Error:', error);
      });


    },
    confirmInput(value){
      console.log(value)
      console.log(this.inputAreaType)
      switch (this.inputAreaType){
        case 2:this.inputData[this.currentModel]=this.getStringDate(value);break;
        case 4:this.inputData[this.currentModel]=value;break;
        case 5:
          if(!this.inputData[this.currentModel]){
            this.$toast('证件图片未更改或未成功上传');
            return
          }
          this.keyvalue += 1
          break;
        case 6:
          if(!this.inputData[this.currentModel]){
            this.$toast('图片未更改或未成功上传');
            return
          }
          this.keyvalue += 1
          break;
      }
      this.cancelInput()
    },
    cancelInput(){
      this.inputAreaType = 0
      this.currentModel =""
    },
    celanForm(){
      this.intoUserMaterials()
      this.clearFormData()
    },
    clearFormData(){
      this.inputData = {}
      this.onlineFormData = []
      this.currentSelects = []
      this.currentModel = ""
      this.currentMaterialId = ""
      this.currentMaterialName = ""
      this.signaturePad = null
      this.tableObj = {}
      this.cancelInput()
      if(this.popupScrollObj!=null){
        this.popupScrollObj.destroy();
        this.popupScrollObj = null;
      }
    },
    // 日期格式化
    getStringDate(date){
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');

      const stringDate = `${year}-${month}-${day}`;
      return stringDate
    },
    addTableItem(model){
      var templateData
      this.onlineFormData.forEach(item=>{
        if(item.model === model){
          templateData = item.tableColumns
        }
      })
      this.tableObj[model].push(templateData)
      this.inputData[model].push({})
      this.$nextTick(() => {
        this.popupScrollObj.refresh()
      })
    },
    //历史清单记录
    intoUserMaterials() {
      const url = `https://www.pengzhou.org.cn/api/znsp/intoUserMaterials`;
      axios.post(url, {
        oid:this.$route.query.id,
        id:this.currentMaterialId,
        content:JSON.stringify(this.inputData)
      }, {
        headers: {
          'token': this.token,
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
      }).catch(error => {
      });
    },
    //清单填充
    findContenHistory(id) {
      const url = `https://www.pengzhou.org.cn/api/znsp/findContenHistory?id=` + id;
      axios.get(url, {}, {
        headers: {
          'token': this.token,
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }
      }).then(response => {
        if (response.data.data && response.data.success) {
          this.inputData = JSON.parse(response.data.data)
          console.log(this.inputData)
        }
      }).catch(error => {
      });
    },
    //事项办理材料清单
    findMatterMaterial() {
      const url = `https://www.pengzhou.org.cn/api/znsp/findMatterMaterial?id=` + this.id;
      axios.get(url, {}, {
        headers: {
          'token': this.token,
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }
      }).then(response => {
        if (response.data && response.data.success) {
          this.MaterialList = this.processedList(response.data.data)
          this.title =  response.data.mattername + "网上预审"
          this.loadingStatus = 1
          this.$nextTick(() => {
            this.scrollObj = new BScroll(this.$refs.scrollWrap, {
              click: true,
            })
          })
        } else {
          this.loadingStatus = -1
        }
      }).catch(error => {
        this.loadingStatus = -1
        console.error('Error:', error);
      });
    },
    //电子表单清单
    getForm(id) {
      this.findContenHistory(id)
      const url = `https://www.pengzhou.org.cn/api/znsp/getFormById?id=` + id;
      axios.get(url, {}, {
        headers: {
          'token': this.token,
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }
      }).then(response => {
        if (response.data && response.data.success) {
          this.onlineFormData = response.data.data
          response.data.data.forEach(item=>{
            if(item.type=='table'){
              this.tableObj[item.model]=[]
              this.tableObj[item.model].push(item.tableColumns)
              this.inputData[item.model]=[]
              this.inputData[item.model].push({})
            }
          })
          this.$nextTick(() => {
            this.popupScrollObj = new BScroll(this.$refs.popupScrollWrap, {
              click: true,
            })
            // this.popupScrollObj.addEventListener('touchmove', (event)=>{
            //   event.preventDefault()
            // });
          })
          for(let i=0;i<this.onlineFormData.length;i++){
            if(this.onlineFormData[i].model == 'company'){
              if(this.company)
              this.inputData[this.onlineFormData[i].model] = this.company.name
            }else if(this.onlineFormData[i].model == 'creditcode'){
              if(this.company)
                this.inputData[this.onlineFormData[i].model] = this.company.regNum
            }else if(this.onlineFormData[i].model == 'operate'){
              if(this.company)
                this.inputData[this.onlineFormData[i].model] = this.company.address
            }else if(this.onlineFormData[i].model == 'name'){
              if(this.userName !== ''){
                this.inputData[this.onlineFormData[i].model] = this.userName
              }
            }else if(this.onlineFormData[i].model == 'sex'){
              if(this.userId !== ''){
                let sex = this.userId.substring(16,17);
                if(sex%2 === 0)
                  sex = '女';
                else
                  sex = '男';
                this.inputData[this.onlineFormData[i].model] = sex
              }
            }else if(this.onlineFormData[i].model == 'family'){
              this.inputData[this.onlineFormData[i].model] = '汉族'
            }else if(this.onlineFormData[i].model == 'cardtype'){
              this.inputData[this.onlineFormData[i].model] = '身份证'
            }else if(this.onlineFormData[i].model == 'idcard'){
              if(this.userId !== '')
              this.inputData[this.onlineFormData[i].model] = this.userId
            }else if(this.onlineFormData[i].model == 'tell'){
                this.inputData[this.onlineFormData[i].model] = this.phoneNumber
            }else if(this.onlineFormData[i].model == 'address'){
              if(JSON.stringify(this.onlineFormData).indexOf('sex') >= 0 ){
                this.inputData[this.onlineFormData[i].model] = this.address
              }else if(this.company){
                this.inputData[this.onlineFormData[i].model] = this.company.address
              }
            }else if(this.onlineFormData[i].model == 'idcard_front'){
              if(this.idcard_front !== ''){
                this.inputData[this.onlineFormData[i].model] = [{"status":"done","file":null,"content":"","url":this.idcard_front,"message":""}]
              }
            }else if(this.onlineFormData[i].model == 'idcard_back'){
              if(this.idcard_back !== ''){
                let file = [{"status":"done","file":null,"content":"","url":this.idcard_back,"message":""}]
                this.inputData[this.onlineFormData[i].model] = file
              }
            }else if(this.onlineFormData[i].model == 'periodofvalidityyear'){
              this.inputData[this.onlineFormData[i].model] = '5'
            }
          }
          console.log(this.inputData)
          this.onlineFormStatus = 1
        } else {
          this.formShow = false
          this.$toast('材料表单获取失败');
        }
      }).catch(error => {
        this.formShow = false
        this.$toast('材料表单获取失败');
        console.error('Error:', error);
      });
    },
    onlineForm(item) {
      this.getForm(item.id)
      this.formShow = true
      this.currentMaterialId = item.id
      this.currentMaterialName = item.materialname
    },
    downloadBlank(url){
      this.$router.push({
        path: '/download',
        query: {
          url: url,
        }
      })
    },
    verifyNumber(phone) {
      if ((/^1[345789]\d{9}$/.test(phone))) {
        return true
      } else {
        return false
      }
    },
    deleteImg(file, name) {
      this.newUploadObj=this.newUploadObj.filter(item => item.name !== name);
      this.items=this.items.filter(item => item.name !== name);
    },
    deleteCardImg(file,id){
      // if (id in this.inputData) {
      //   delete this.inputData[id];
      // }
      this.inputData[id]=[]
    },
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/heic' || file.type == '') {
        return true
      }
      this.$toast.fail("请上传图片格式的身份证材料！")
      return false
    },
    onOversize() {
      this.$toast.fail("图片大小不能超过10M！")
    },
    submit() {
      if (this.phoneNumber == "") {
        this.$toast('手机号码不能为空');
        return
      }else {
        if(this.newMaterialA.length == 0 || this.newMaterialA[0].url == '' || this.newMaterialB.length == 0 || this.newMaterialB[0].url == ''){
          this.$toast('身份证正反面材料上传不全，请核查');
          return
        }
        //上传材料比对
        let checkValue = []
        this.MaterialList.forEach((item,indexs) => {
          if(item.required !== 'true'){
            checkValue.push(item)
          }else{
            this.newUploadObj.forEach((map,index) => {
              if(item.materialname == map.name  && map.url !== ''){
                checkValue.push(item)
              }
            })
          }
        })
        //核对未上传的材料
        let nowList = this.MaterialList.filter(function (item) {
          return !checkValue.includes(item)
        })
        if(nowList.length >=1){
          if(nowList.length >= 2){
            this.$toast('材料上传不全，请核查');
          }else{
            this.$toast(nowList[0].materialname+'材料上传不全，请核查');
          }
        }else{
          //提交数据
          const url = "https://www.pengzhou.org.cn/api/znsp/intoZNSPValue";
          axios.post(url, {
            idcard: this.userId,
            name: this.userName,
            tell: this.phoneNumber,
            oid: this.$route.query.id,
            json: JSON.stringify(this.newUploadObj)
          }, {
            headers: {
              'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
            }
          }).then(response => {
            if (response.data && response.data.success) {
              //提交成功
              window.location.href = response.data.url;
            } else {
              this.$toast(response.data.msg);
            }
          }).catch(error => {
            console.error('Error:', error);
          });
        }
      }
    },
    startUpload(file, flag) {
      file.status = 'uploading';
      let formData = new FormData();
      if (file instanceof Array && file.length) {
        for (let i = 0; i < file.length; i++) {
          const element = file[i].file;
          formData.append("file[]", element);
        }
      } else {
        formData.append("file", file.file);
      }
      //上传接口
      let typename = "";
      if (flag.name.indexOf("身份证") > -1) {
        typename = "idcard"
      } else if (flag.name.indexOf("营业执照") > -1) {
        typename = "bizLicense"
      }
      const url = "https://www.pengzhou.org.cn/api/znsp/ocrResult?type=" + typename + "&fileName=" + flag.name;
      try {
        axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          if (response.data && response.data.success) {
            let checklist = {
              name: flag.name
            }
            this.addItem(checklist)
            //上传成功未入库
            file.status = 'done';
            file.file = null
            file.content = ""
            file.url = response.data.url
            if (typename == "idcard") {
              if (response.data.name !== undefined){
                this.userName = response.data.name
                this.idcard_front = response.data.url
              }else{
                this.idcard_back = response.data.url
              }
              if (response.data.idcard !== undefined)
                this.userId = response.data.idcard
              if (response.data.address !== undefined)
                this.address = response.data.address
            }else if(typename == "bizLicense") {
              this.company = response.data.company
            }
            let valueList = {
              url: response.data.url,
              name: flag.name
            }
            this.newUploadObj.push(valueList)
            this.scrollObj.refresh()
          } else {
            file.status = 'done';
            file.file = null
            file.content = ""
            file.url = ""
            this.$toast('文件格式有误！');
          }
        }).catch(error => {
          console.error('Error:', error);
        });
      } catch (error) {
        this.$toast('获取验证码失败');
        console.error('请求失败:', error);
      }
    },
  }
}
</script>

<style scoped>
.ai_wrap {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-size: contain;
  text-align: left;
}

.top_wrap {
  width: 100%;
  background: #5482eb;
  display: flex;
  padding: 16px;
  align-items: center;
}

.icon {
  width: 2em;
  height: 2em;
  margin-right: 5px;
}

.business_title {
  font-size: 1rem;
  font-weight: normal;
  color: #fff;
}

/deep/ .van-field--disabled .van-field__label {
  color: #4d4d4d;
  font-size: 0.9rem;
}

.form_dt {
  width: 90%;
  color: #4d4d4d;
  font-size: 0.9rem;
  margin: 1rem 1rem 0 1rem;
  display: flex;
}

.idcard_a, .hkb {
  margin-left: 1rem;
}

.upload_row {
  overflow: hidden;
  margin-top: 0.5rem;
}

.nt2 {
  color: #adabab;
  margin-left: 0.5rem;
  font-size: 0.8rem;
}

.content {
  padding-bottom: 20px;
}

.required p:before {
  content: "*";
  color: red;
  margin-right: 4px;
}
.required1 span:before {
  content: "*";
  color: red;
  margin-right: 4px;
}

.required {
  display: flex;
}

.form_dt p,.required p {
  flex: 1;
}
.form_dt span{
  margin-left: 5px;
}

.error_area {
  padding: 1rem;
  text-align: center;
  color: #888080;
}

.retry {
  color: #5482eb
}

.form_area {
  /*padding: 2rem 0.8rem 0 0.8rem;*/
  height:92%;
  box-sizing: border-box;
  overflow: hidden;
}
.popup_con{
  padding: 2rem 0.8rem 20px 0.8rem;
}
.form_area h6 {
  color: #5482eb;
  font-size: 14px;
  padding-left: 8px;
  padding-bottom: 5px;
  height:30px;
  line-height: 30px;
}
.table_con .van-field{
  background:#f8f8f8;
}
.table_wrap{
  margin:10px 0 20px 0;
}
.setting_area {
  min-height: 3rem;
  width: 96%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  border-bottom: dotted 1px #e3e3e3;
}

.setting_area span {
  color: #646566;
  flex: 1;
  text-align: left;
}

.sign_img {
  height: 1.5rem;
  margin-right: 0.8rem;
}

.setting_area .van-field {
  padding-left: 0 !important;
}
.form_btn{
  width:90%;
  position: absolute;
  bottom:10px;
  left:5%;
}
.id_pop{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -60px;
  margin-top: -60px;
}
.table_title{
  width:100%;
  padding:8px 0;
  background:#e2e2e2;
  display: flex;
  align-items: center;
  border-radius: 6px 6px 0 0;
}
.table_title span{
  padding-left: 8px;
  text-align: left;
  flex:1;
}
.table_title .add_icon{
  width:16px;
  height:16px;
  margin-right: 8px;
}
.sampleDownload{
  width:90%;
  margin: 0.4rem 1rem 0 1rem;
  display: flex;
  justify-content: flex-end;
}
/deep/ .material_item .van-cell__value {
  flex: none;
  width: 0;
}

/deep/ .van-image__img {
  object-fit: contain !important;
}

/deep/ .idcard_a .van-uploader__upload {
  background: url("../assets/idcard0.png") #f7f8fa center center no-repeat;
  background-size: contain;
}

/deep/ .idcard_b .van-uploader__upload {
  background: url("../assets/idcard1.png") #f7f8fa center center no-repeat;
  background-size: contain;
}

/deep/ .van-uploader {
  float: left;
}
/deep/ .van-popup{
  overflow: hidden;
}
/deep/ .van-checkbox{
  margin:12px 18px;
}
</style>
